from django.shortcuts import render, render_to_response
from django.http.response import HttpResponse, HttpResponseRedirect
from django.http import JsonResponse
from django.core.urlresolvers import reverse
from django.contrib.auth.decorators import login_required
from django.db.models import Q
import json

from api.salt_api import SaltAPI
from oms import settings


# Create your views here.

@login_required()
def key_list(request):
    header_title, sub_title, path1, path2 = "", "", "配置平台", "key管理"

    return render(request, 'configs/key_list.html', locals())


# todo:客户端分页
@login_required()
def get_accepted_key(request):
    """
    获取已允许的key
    :param request:
    :return:
    """
    salt_api = SaltAPI(apiurl=settings.SALT_API['apiurl'], username=settings.SALT_API['user'],
                       password=settings.SALT_API['password'])

    minions, minions_pre = salt_api.list_all_key()
    rows = [{
        'hostname': host,
        'status': 'ok',

    } for host in minions]
    return HttpResponse(json.dumps(rows))


@login_required()
def get_unaccepted_key(request):
    """
    获取未允许的key
    :param request:
    :return:
    """
    salt_api = SaltAPI(apiurl=settings.SALT_API['apiurl'], username=settings.SALT_API['user'],
                       password=settings.SALT_API['password'])

    minions, minions_pre = salt_api.list_all_key()
    rows = [{
        'hostname': host
    } for host in minions_pre]
    return HttpResponse(json.dumps(rows))


@login_required()
def accept_key(request):
    """
    accept salt minions key
    :param request:
    :return:
    """
    ret = {'Code': 0, 'Message': ''}
    node_list = request.POST.getlist('node_list[]')
    salt_api = SaltAPI(apiurl=settings.SALT_API['apiurl'], username=settings.SALT_API['user'],
                       password=settings.SALT_API['password'])
    for node in node_list:
        retval = salt_api.accept_key(node)
        ret['Code'] = 1
        ret['Message'] = '执行成功'
    return HttpResponse(json.dumps(ret))


@login_required()
def delete_key(request):
    """
    delete salt minions key
    :param request:
    :return:
    """
    ret = {'Code': 0, 'Message': ''}
    node_list = request.POST.getlist('node_list[]')
    salt_api = SaltAPI(apiurl=settings.SALT_API['apiurl'], username=settings.SALT_API['user'],
                       password=settings.SALT_API['password'])
    # return HttpResponse('oK')
    for node in node_list:
        salt_api.delete_key(node)
        ret['Code'] = 1
        ret['Message'] = '执行成功'
    return HttpResponse(json.dumps(ret))
